package com.meilai.project.controller.db;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.meilai.project.dto.CommonResult;
import com.meilai.project.entity.personnel.org.Department;
import com.meilai.project.entity.system.Accounting;
import com.meilai.project.entity.system.User;
import com.meilai.project.entity.system.UserDepartmentRelation;
import com.meilai.project.mapper.personnel.org.DepartmentMapper;
import com.meilai.project.mapper.system.AccountingMapper;
import com.meilai.project.service.personnel.org.DepartmentService;
import com.meilai.project.service.personnel.org.RoleService;
import com.meilai.project.service.system.AccountingService;
import com.meilai.project.service.system.UserDepartmentRelationService;
import com.meilai.project.service.system.UserService;
import com.meilai.project.util.BCrypt;
import com.meilai.project.util.DateUtil;
import com.meilai.project.util.RegexUtil;
import com.meilai.project.vo.db.SystemVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Api(value = "导入用户数据", description = "导入用户数据")
@RestController
@RequestMapping("public/web/import")
public class ImportSystemData {

    @Autowired
    UserService userService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    RoleService roleService;
    @Autowired
    AccountingService accountingService;
    @Autowired
    AccountingMapper accountingMapper;
    @Autowired
    UserDepartmentRelationService userDepartmentRelationService;


    @PostMapping( "/system")
    @ApiOperation(value = "导入用户数据")
    @Transactional
    public CommonResult importData(@RequestParam("file") MultipartFile file)
            throws IOException {
        List<SystemVO> list = new ArrayList<>();
        ExcelReader excelReader = EasyExcel.read(file.getInputStream(), SystemVO.class,
                new AnalysisEventListener<SystemVO>(){
                    @Override
                    public void invoke(SystemVO data, AnalysisContext context) {
                        list.add(data);
                    }
                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                    }
                }).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        excelReader.finish();
        User user1 = new User();
        user1.setName("超管");
        user1.setUsername("admin");
        user1.setSex("男");
        user1.setStatus(1);
        user1.setType(1);
        user1.setMobile("13771071503");
        user1.setLast_login_type(2);
        user1.setSort(1);
        user1.setEmail("601995227@qq.com");
        user1.setPassword(BCrypt.hashpw("123456",BCrypt.gensalt()));
        userService.save(user1);
        list.forEach(data -> {
            Department department = saveDepartment(data);
            User user = saveUser(data);
            saveUserDepartment(user,department,data);
            saveAccounting(user.getId(),department.getId());
        });
        return new CommonResult().success(list);
    }

    private UserDepartmentRelation saveUserDepartment(User user,Department department,SystemVO data){
        UserDepartmentRelation relation = new UserDepartmentRelation();
        relation.setDepartment_id(department.getId());
        relation.setUser_id(user.getId());
        relation.setJob(data.getJob());
        userDepartmentRelationService.save(relation);
        return relation;
    }

    private long departmentTopId = 0;
    private Department saveDepartment(SystemVO data){
        if("总经理".equals(data.getAssignCompanyName())){
            Department departmentCompany = new Department();
            departmentCompany.setCreated_at(LocalDateTime.now());
            departmentCompany.setName(data.getAssignCompanyName());
            departmentCompany.setStatus(1);
            departmentCompany.setPid(null);
            departmentService.save(departmentCompany);
            departmentTopId = departmentCompany.getId();
            return departmentCompany;
        }
        //分公司
        Department departmentCompany = new Department();
        Department departmentCompanyDb = departmentMapper.selectByCompanyName(data.getAssignCompanyName());
        if(departmentCompanyDb!=null){
            departmentCompany = departmentCompanyDb;
        }else{
            departmentCompany.setCreated_at(LocalDateTime.now());
            departmentCompany.setName(data.getAssignCompanyName());
            departmentCompany.setStatus(1);
            departmentCompany.setPid(departmentTopId);
            departmentService.save(departmentCompany);
        }
        //部门
        Department departmentDb = departmentMapper.selectByPidAndName(departmentCompany.getId(),data.getDepartmentName());
        if(departmentDb==null){
            Department department = new Department();
            department.setPid(departmentCompany.getId());
            department.setName(data.getDepartmentName());
            department.setStatus(1);
            department.setCreated_at(LocalDateTime.now());
            departmentService.save(department);
            return department;
        }
        return departmentDb;
    }

    private void saveAccounting(long userId,long departmentId){
        List<Accounting> accountingDbs = accountingMapper.selectByUserIdAndDepartmentId(userId,departmentId);
        if(accountingDbs==null||accountingDbs.size()==0){
            Accounting accounting = new Accounting();
            accounting.setCreated_at(LocalDateTime.now());
            accounting.setUser_id(userId);
            accounting.setDepartment_id(departmentId);
            accounting.setMain(true);
            accounting.setActive(true);
            accountingService.insert(accounting);
        }
    }

    private User saveUser(SystemVO data){
        User user = new User();
        user.setCreated_at(LocalDateTime.now());
        user.setUsername(data.getMobile());
        user.setName(data.getName());
        user.setPassword(BCrypt.hashpw("123456",BCrypt.gensalt()));
        user.setStatus(1);
        userService.save(user);
        return user;
    }

    private String convertCompanyAge(String companyAge){
        if(StringUtils.isEmpty(companyAge)){
            return null;
        }
        String result = RegexUtil.replaceChinese(companyAge,",");
        return result.substring(0,result.length() - 1);
    }

    private LocalDateTime convertByString(String input,String symbol){
        String[] date = input.split(symbol);
        return LocalDateTime.of(
                Integer.parseInt(date[0]),
                Integer.parseInt(date[1]),
                Integer.parseInt(date[2]),0,0
        );
    }


    private LocalDateTime convertBirth(String date1,String date2){
        int nowYear = StringUtils.isEmpty(date1)?LocalDateTime.now().getYear():Integer.parseInt(RegexUtil.replaceChinese(date1,""));
        int[] birth = {nowYear,LocalDateTime.now().getMonthValue(),LocalDateTime.now().getDayOfMonth()};
        if(StringUtils.isNotEmpty(date2)){
            String[] monthDay = date2.replaceAll("（农历）","").split("\\.");
            int month = Integer.parseInt(monthDay[0]);
            int day = Integer.parseInt(monthDay[1]);
            birth = new int[]{nowYear,month,day};
            if(date2.indexOf("农历")!=-1){
                birth = DateUtil.lunarToSolar(nowYear,month,day,false);
            }
        }
        return LocalDateTime.of(
                birth[0],
                birth[1],
                birth[2],0,0);
    }
}
